const App = getApp();
const func = require('../../utils/func');
const util = require('../../utils/util.js');
import setting from '../../setting.js';
let globalData = getApp().globalData;

// 地址类型
let addressLabel = setting.addressLabel;

Page({
    // 页面的初始数据
    data: {
        // 会员留言
        remark: '',
        wechatMoney:'true',
        // 订单标识
        cookieID: 0,
        // 商品列表
        goodsList: {},
        // 是否加载中
        isLoading: true,
        // 立即购买是否付款完成，默认 false ，未付款
        is_buy_pay: false,
        // 购物车是否付款完成，默认 false ，未付款
        is_cart_pay: false,
        // 是否允许余额支付
        allowMoneyPay: true,
        // 是否使用余额支付
        useUsersMoney: false,
        // 支付名称
        submitTitle: '提交订单',
        // 支付按钮颜色
        background: '#eb0909 !important',
        // 小程序消息模板信息
        tmplData: [],
        // 小程序消息模板ids
        tmplIds: [],
        // 使用优惠券的index
        couponIndex: 0,
        // 显示优惠券弹窗列表
        showCoupon: false,
        // 显示积分弹窗列表
        showScores: false,
        // 显示余额弹窗列表
        showBalance: false,
        // 是否已提交支付
        submitPay: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        var _this = this;

        // 当前页面参数
        _this.setData({
            cookieID: options.cookieID ? options.cookieID : 0,
            cartSubmit: options.cartSubmit ? options.cartSubmit : 0,
        });
        let obj = wx.getMenuButtonBoundingClientRect()
        setTimeout(() => {
            wx.getSystemInfo({
                success: res => {
                    this.setData({
                        width: obj.left || res.windowWidth,
                        height: obj.top ? obj.top + obj.height + 8 : res
                            .statusBarHeight + 44,
                        top: obj.top ? obj.top + (obj.height - 32) / 2 : res
                            .statusBarHeight + 6,
                        scrollH: res.windowWidth,
                        topHeight:obj.height
                    }, () => {
                        
                        globalData.navigationBarWidth = this.data.width
                        globalData.navigationBarHeight = this.data.height
                        globalData.statusBarHeight = res.statusBarHeight
                    })
                }
            });
        }, 0);
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // 获取当前订单信息
        let _this = this;
        if (!_this.data.submitPay) _this.getOrderData();
    },

    // 下拉刷新
    onPullDownRefresh() {
        let _this = this;
        // 获取当前订单信息
        _this.getOrderData();
        wx.stopPullDownRefresh();
    },

    // 获取当前订单信息
    getOrderData() {
        let _this = this;
        if (_this.data.is_buy_pay && _this.data.cookieID) {
            return false;
        } else if (_this.data.is_cart_pay && !_this.data.cookieID) {
            return false;
        } else {
            let postData = {
                cookieID: _this.data.cookieID,
                cartSubmit: _this.data.cartSubmit
            };

            App._requestApi(_this, App.globalData.config.shopGoodsBuyUrl, postData,
                function (res) {
                    let address = res.data.address;
                    let userInfo = res.data.userInfo;
                    let goodsList = res.data.goodsList;
                    let globalParam = res.data.globalParam;
                    let useFindCoupon = res.data.useFindCoupon;
                    let useAllCoupon = res.data.goodsCoupon['useAllCoupon'];
                    let donUseAllCoupon = res.data.goodsCoupon['donUseAllCoupon'];
                    // if (useAllCoupon) {
                    //     useAllCoupon.forEach((value, index) => {
                    //         value["coupon_price"] = parseInt(value["coupon_price"])
                    //     });
                    // }
                    // if (donUseAllCoupon) {
                    //     donUseAllCoupon.forEach((value, index) => {
                    //         value["coupon_price"] = parseInt(value["coupon_price"])
                    //     });
                    // }
                    address['labelName'] = address.label ? addressLabel[address['label']] : '';
                    let prom_type = _this.data.prom_type;
                    let exist_address = address.addr_id ? true : false;
                    _this.setData({
                        address,
                        userInfo,
                        goodsList,
                        globalParam,
                        useAllCoupon,
                        useFindCoupon,
                        donUseAllCoupon,
                        isLoading: false,
                        prom_type,
                        exist_address,
                    });
                },
                function (res) {
                    App.showError(res.msg);
                }
            );
        }
    },

    back: function() {
        let pages = getCurrentPages();
        wx.navigateBack();
    },

    // 展示弹窗
    couponShowPopup() {
        let _this = this;
        // 还原已确认的优惠券标记
        let couponIndex = _this.data.couponIndex;
        let useAllCoupon = _this.data.useAllCoupon;
        if (useAllCoupon) {
            useAllCoupon.forEach((value, index) => {
                if (1 === parseInt(value["default"])) couponIndex = index;
            });
        }
        _this.setData({
            couponIndex,
            showCoupon: !_this.data.showCoupon
        });
    },

    // 点击使用优惠券
    couponUseAction(e) {
        let _this = this;
        // 标记使用优惠券的选中效果
        _this.setData({ couponIndex: e.currentTarget.dataset.index });
    },

    // 取消优惠券操作
    couponCancelAction() {
        let _this = this;
        _this.couponShowPopup();
    },

    // 确认优惠券操作
    couponConfirmAction() {
        let _this = this;
        // 根据标记匹配使用的优惠券
        let couponIndex = _this.data.couponIndex;
        let useAllCoupon = _this.data.useAllCoupon;
        let useFindCoupon = _this.data.useFindCoupon;
        if (useAllCoupon) {
            useAllCoupon.forEach((value, index) => {
                if (parseInt(couponIndex) === parseInt(index)) {
                    value["default"] = 1;
                    useFindCoupon = value;
                } else {
                    value["default"] = 0;
                }
            });
        }

        _this.setData({
            useAllCoupon,
            useFindCoupon,
            showCoupon: !_this.data.showCoupon
        });

        // 重新计算支付金额
        _this.orderAmountHandle();
    },

    // 显示/隐藏弹窗
    scoresShowPopup() {
        let _this = this;
        _this.setData({
            showScores: !_this.data.showScores
        });
    },

    // 点击使用使用积分
    scoresUseAction(e) {
        let _this = this;
        // 全局参数
        let globalParam = _this.data.globalParam;
        // 标记使用积分的选中效果
        globalParam['useScorePay'] = parseInt(e.currentTarget.dataset.index);
        // 覆盖数据
        _this.setData({ globalParam });
        // 重新计算支付金额
        _this.orderAmountHandle();
        // 显示/隐藏弹窗
        _this.scoresShowPopup();
    },

    // 显示/隐藏弹窗
    balanceShowPopup() {
        let _this = this;
        _this.setData({
            showBalance: !_this.data.showBalance
        });
    },

    // 点击使用使用余额
    balanceUseAction(e) {
        let _this = this;
        // 全局参数
        let globalParam = _this.data.globalParam;
        // 标记使用余额的选中效果
        globalParam['useBalancePay'] = parseInt(e.currentTarget.dataset.index);
        // 覆盖数据
        _this.setData({ globalParam });
        // 重新计算支付金额
        _this.orderAmountHandle();
        // 显示/隐藏弹窗
        _this.balanceShowPopup();
    },

    // 重新计算支付金额
    orderAmountHandle() {
        let _this = this;
        // 全局参数
        let globalParam = _this.data.globalParam;
        // 使用的优惠券
        let useFindCoupon = _this.data.useFindCoupon;
        // 最终支付总金额 = 订单商品总额 + 订单运费
        globalParam['orderAmount'] = Number(globalParam['orderTotalAmount']) + Number(globalParam['shippingFee']);
        // 获取优惠券金额
        globalParam['couponPrice'] = useFindCoupon['coupon_price'] ? Number(useFindCoupon['coupon_price']) : 0;
        // 最终支付总金额 = 最终支付总金额 - 优惠券金额
        globalParam['orderAmount'] = Number(globalParam['orderAmount']) - Number(globalParam['couponPrice']);
        globalParam['payUseCash'] = parseFloat(globalParam['orderAmount']);

        // 使用积分
        if (1 === parseInt(globalParam['scoreDeductionType'])) {
            // 最多可使用多少积分
            var payUseScoresNum = parseInt(globalParam['usersScores']) > parseInt(globalParam['scoreDeductionMaxScore']) ? globalParam['scoreDeductionMaxScore'] : globalParam['usersScores'];
            // 积分可抵扣多少金额
            var payUseScores = parseInt(payUseScoresNum) / parseInt(globalParam['scoreDeductionScore']);
            // 如果抵扣金额不为整数则再次重新计算
            if (!_this._isInteger(payUseScores)) {
                payUseScores = parseInt(String(payUseScores).split('.')[0]);
                payUseScoresNum = parseInt(payUseScores) * parseInt(globalParam['scoreDeductionScore']);
            }
            // 如果抵扣金额大于需要支付的金额则执行重新计算
            if (parseFloat(payUseScores) > parseFloat(globalParam['payUseCash'])) {
                if (1 === parseInt(globalParam.useScorePay)) globalParam['useBalancePay'] = 0;
                payUseScores = parseFloat(globalParam['payUseCash']);
                payUseScoresNum = parseInt(Math.ceil(parseFloat(payUseScores) * parseFloat(globalParam['scoreDeductionScore'])));
            }
        } else if (0 === parseInt(globalParam['scoreDeductionType'])) {
            // 计算积分最多可抵扣订单的多少金额
            var payUseScores = Math.ceil(parseFloat(globalParam['payUseCash']) * parseFloat(parseInt(globalParam['scoreDeductionMaxPercent']) / 100));
            // 计算抵扣需要多少个积分
            var payUseScoresNum = parseInt(payUseScores) * parseInt(globalParam['scoreDeductionScore']);
            // 计算用户是否有足够的积分进行抵扣，如果不够则执行
            if (parseInt(globalParam['usersScores']) < parseInt(payUseScoresNum)) {
                // 将用户的积分覆盖订单最大使用积分
                payUseScoresNum = globalParam['usersScores'];
                // 重新积分用户可抵扣金额和使用积分
                payUseScores = parseInt(payUseScoresNum) / parseInt(globalParam['scoreDeductionScore']);
                // 如果抵扣金额不为整数则再次重新计算
                if (!_this._isInteger(payUseScores)) {
                    payUseScores = parseInt(String(payUseScores).split('.')[0]);
                    payUseScoresNum = parseInt(payUseScores) * parseInt(globalParam['scoreDeductionScore']);
                }
            }
        }
        globalParam['payUseScoresNum'] = payUseScoresNum ? parseInt(payUseScoresNum) : 0;
        globalParam['payUseScores'] = payUseScores ? parseFloat(payUseScores.toFixed(2)) : 0;
        if (1 === parseInt(globalParam.useScorePay)) {
            globalParam['payUseCash'] = parseFloat(Number(globalParam['payUseCash']) - Number(globalParam['payUseScores']));
        }

        // 使用余额
        if (Number(globalParam['usersMoney']) > Number(globalParam['payUseCash'])) {
            globalParam['payUseBalance'] = parseFloat(globalParam['payUseCash'].toFixed(2));
            if (1 === parseInt(globalParam.useBalancePay)) globalParam['payUseCash'] = 0;
        } else {
            globalParam['payUseBalance'] = parseFloat(globalParam['usersMoney'].toFixed(2));
            if (1 === parseInt(globalParam.useBalancePay)) globalParam['payUseCash'] = Number(globalParam['payUseCash']) - Number(globalParam['payUseBalance']);
        }

        // 支付金额处理
        globalParam['payUseCash'] = String(parseFloat(globalParam['payUseCash'].toFixed(2)));
        globalParam['payUseCashArr'] = globalParam['payUseCash'].split('.');

        _this.setData({ globalParam });
    },

    // 判断是否为整数
    _isInteger(value) {
        return Math.floor(value) === value;
    },

    // 移除商品(将购物车指定商品设为非选中)
    removeGoods(e) {
        var cart_id = e.currentTarget.dataset.cartid;
        var goods_id = e.currentTarget.dataset.goodsid;
        if (cart_id && goods_id) {
            let _this = this;
            wx.showModal({
                title: "温馨提示",
                content: "确认移除商品？(购物车不移除)",
                success(o) {
                    if (o.confirm) {
                        let postData = {
                            action: 'remove',
                            cart_id: cart_id,
                            goods_id: goods_id
                        };
                        App._requestApi(_this, App.globalData.config.shopCartActionUrl, postData,
                            function(res) {
                                App.showSuccess(res.msg, function() {
                                    _this.getOrderData();
                                });
                            },
                            function(res) {
                                App.showError(res.msg);
                            }
                        );
                    }
                }
            });
        }
    },
    // 积分抵扣按钮切换
    changejifen(e){
        this.setData({
            switchChecked:e.detail.value
        })

    },
    // 余额抵扣按钮切换
    changemoney(e){
        this.setData({
            changemoney:e.detail.value
        })

    },

    // 订单支付选择
    orderSelectPay(e) {
        let _this = this;
        // 是否允许余额支付
        let allowMoneyPay = true;
        // 是否使用余额支付
        let useUsersMoney = false;
        // 是否选中余额支付
        let isChecked = e.detail.value;
        // 确认订单按钮颜色
        let background = '#eb0909 !important';
        // 确认订单按钮标题
        let submitTitle = _this.data.submitTitle;
        if (true === isChecked) {
            // 获取会员余额
            let usersMoney = Number(_this.data.userInfo.users_money);
            // 获取支付总额
            let orderAmount = Number(_this.data.globalParam.orderAmount);
            if (usersMoney < orderAmount) {
                allowMoneyPay = false;
                submitTitle = '余额不足';
                background = '#9e9e9e !important';
            } else {
                useUsersMoney = true;
                submitTitle = '余额支付';
            }
        } else {
            submitTitle = '微信支付';
        }
        _this.setData({submitTitle: submitTitle, useUsersMoney: useUsersMoney, background: background, allowMoneyPay: allowMoneyPay});
    },

    // 买家留言
    bindRemark(e) {
        let _this = this;
        _this.setData({remark: e.detail.value});
    },

    // 订单提交并执行支付
    orderSubmitPay(e) {
        let _this = this;
        // let allowMoneyPay = _this.data.allowMoneyPay;
        // if (false === allowMoneyPay) return false;

        var allow = e.currentTarget.dataset.allow;
        if (0 === parseInt(allow)) {
            App.showError('部分商品不在配送区域内，请移除再提交');
        } else if (1 === parseInt(allow)) {
            // 是否使用余额支付
            // var useUsersMoney = _this.data.useUsersMoney ? 1 : 0;
            let postData = {
                // useUsersMoney: useUsersMoney,
                remark: _this.data.remark || '',
                cookieID: _this.data.cookieID || '',
                cartSubmit: parseInt(_this.data.cartSubmit) || 0,
                addrID: parseInt(_this.data.address.addr_id) || 0,
                useID: parseInt(_this.data.useFindCoupon['use_id']) || 0,
                useScorePay: _this.data.globalParam['useScorePay'] || 0,
                useBalancePay: _this.data.globalParam['useBalancePay'] || 0,
            };

            // 提交订单
            App._requestApi(_this, App.globalData.config.shopOrderPayUrl, postData,
                function(res) {
                    _this.data.tmplData = res.data.tmplData;
                    for (let key in _this.data.tmplData) {
                        _this.data.tmplIds.push(_this.data.tmplData[key]['template_id']);
                    }
                    
                    let order_id = res.data.orderData.order_id;
                    let order_code = res.data.orderData.order_code;
                    _this.setData({order_id, order_code});
                    
                    // 订单选择微信支付
                    let pay_use_cash = res.data.orderData.pay_use_cash;
                    if (parseFloat(pay_use_cash) > parseFloat(0)) {
                        if (res.data.weChatPay.return_code == 'FAIL') {
                            App.showError(res.data.weChatPay.return_msg);
                            return false;
                        }
                        App.wxPayment({
                            order_id: order_id,
                            payment: res.data.weChatPay,
                            success: res1 => {
                                _this.setData({
                                    is_buy_pay: _this.data.cookieID ? true : false,
                                    is_cart_pay: _this.data.cookieID ? false : true,
                                });
                                // 执行订单支付后续处理
                                _this._orderPayHandle();
                            },
                            fail: res1 => {
                                _this.data.submitPay = true;
                                if ('requestPayment:fail cancel' == res1.errMsg) {
                                    wx.redirectTo({
                                        url: '/pages/order/detail?order_id=' + order_id,
                                    });
                                }
                                if (!res.msg.error) {
                                    App.showError(res.msg.error);
                                }
                            }
                        });
                    }
                    // 订单选择余额支付
                    else if (parseFloat(pay_use_cash) <= parseFloat(0)) {
                        if (_this.data.tmplIds.length > 0) {
                            wx.requestSubscribeMessage({
                                tmplIds: _this.data.tmplIds,
                                success (res1) {
                                    let is_send = false;
                                    for (let key in res1) {
                                        if (_this.data.tmplData[key] && 5 == _this.data.tmplData[key]['send_scene'] && 'accept' == res1[key]) {
                                            if (is_send === false) {
                                                is_send = true;
                                            }
                                            App._requestApi(_this, App.globalData.config.apiSendWeixniNoticeUrl, {
                                                result_id: order_id,
                                                send_scene: 5,
                                            }, function(res2) {
                                                _this._redirectToOrderIndex();
                                            },false,false,'正在跳转');
                                        }
                                    }
                                    if (is_send === false) {
                                        _this._redirectToOrderIndex();
                                    }
                                }
                            })
                        } else {
                            App.showSuccess(res.msg, () => {
                                _this._redirectToOrderIndex();
                            });
                        }
                    }
                },
                function(res) {
                    App.showError(res.msg);
                },
                false,
                '支付中'
            );
        }
    },

    // 执行订单支付后续处理
    _orderPayHandle: function () {
        let _this = this;
        let order_id = _this.data.order_id;
        let order_code = _this.data.order_code;
        if (order_id && order_code) {
            let postData = {
                order_id: order_id,
                order_code: order_code
            };
            App._requestApi(_this, App.globalData.config.shopOrderPayHandleUrl, postData,
                function (res) {
                    if (_this.data.tmplIds.length > 0) {
                        wx.requestSubscribeMessage({
                            tmplIds: _this.data.tmplIds,
                            success (res1) {
                                let is_send = false;
                                for (let key in res1) {
                                    if (_this.data.tmplData[key] && 5 == _this.data.tmplData[key]['send_scene'] && 'accept' == res1[key]) {
                                        if (is_send === false) {
                                            is_send = true;
                                        }
                                    }
                                }
                                if (is_send === true) {
                                    App._requestApi(_this, App.globalData.config.apiSendWeixniNoticeUrl, {
                                        result_id: order_id,
                                        send_scene: 5,
                                    }, function(res2) {
                                        wx.redirectTo({url: res.url});
                                    });
                                } else {
                                    wx.redirectTo({url: res.url});
                                }
                            }
                        })
                    } else {
                        App.showSuccess(res.msg, function () {
                            wx.redirectTo({url: res.url});
                        });
                    }
                },
                function (res) {
                    App.showError(res.msg);
                }
            );
        }
    },

    // 跳转到订单列表页
    _redirectToOrderIndex() {
        wx.redirectTo({
            url: '/pages/order/index',
        });
    },

    // 选择收货地址
    selectAddress() {
        let _this = this;
        wx.navigateTo({
            url: '/pages/address/' + (_this.data.exist_address ? 'index?source=goodsBuy' : 'create')
        });
    },
    jumpToUrl(e) {
        func.jumpToUrl(e)
    },
})